﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;

using ThoughtWorks.QRCode.Codec;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Diagnostics;

using Spire.Pdf;
using System.Threading;

namespace PrintReport
{
    public partial class MainForm : Form
    {
        string log_id = "4607";
        string user_id = "";
        int checkLoginPos = -1;
        int refleshReportsPos = -1;
        int checkLoginDec = 3;
        int refleshReportsDec = 300;
        int currentPage = 1;
        int pageSize = 0;
        int sumPage = 0;
        int count = 0;
        const string logid = "https://store.famdr.net/AgentReport/getLogId";
        const string qr = "https://store.famdr.net/AgentReport/LabLogin/log_id/";


        const string generateQRcode = "https://store.famdr.net/AgentReport/generateQrcode";
        const string check = "https://store.famdr.net/AgentReport/checkLogin";
        const string reports = "https://store.famdr.net/AgentReport/getDoctorReport";
        const string log = "https://store.famdr.net/AgentReport/LabPrintReport";
        const string newReports = "http://store1.famdr.net/AgentReport/getPrintReport";
        string currentDirPath = Directory.GetCurrentDirectory();

        public MainForm()
        {
            InitializeComponent();
            //Control.CheckForIllegalCrossThreadCalls = false;
            checkLoginPos = 1;
        }

        /// <summary>
        /// 窗体加载完成后执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Shown(object sender, EventArgs e)
        {

            JObject jo = (JObject)JsonConvert.DeserializeObject(doGet(generateQRcode));
            if (jo != null)
            {
                if ((int)jo["status"] == 1)
                {
                    tsStateBar.Text = "LogId 请求成功，正在生成二维码...";
                    log_id = (string)jo["data"]["log_id"];
                    string qrcode_url = (string)jo["data"]["qrcode_url"];
                    pbCode.Image = CreateImgCode(qrcode_url, 10);
                    gbLogin.Visible = true;
                    tsStateBar.Text = "生成二维码成功，请用微信扫码登录：" + jo["data"]["log_id"];
                }
                else
                {
                    tsStateBar.Text = jo["msg"] + ", error code:" + jo["status"];
                    checkLoginPos = -1;
                    return;
                }
            }
            else
            {
                tsStateBar.Text = "很抱歉，数据请求失败了，请检查你的网络连接。";
                return;
            }

        }

        /// <summary>
        /// 封装Get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns>请求地址的返回值</returns>
        private string doGet(string url)
        {

            try
            {
                WebRequest request = (WebRequest)WebRequest.Create(url);
                request.Method = "GET";
                //request.Accept = "text/html, application/xhtml+xml, */*";
                //request.ContentType = "application/json";    
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader sr = new StreamReader(stream, Encoding.UTF8);
                string ret = sr.ReadToEnd();
                sr.Close();
                stream.Close();
                if (string.IsNullOrEmpty(ret)) return "{\"status\":\"-10000\",\"msg\":\"很抱歉，请求到了空的数据...\"}";
                return ret;
            }
            catch (Exception ex) {
                //MessageBox.Show(ex.Message, "提示");
                return "{\"status\":\"-10000\",\"msg\":\""+ex.Message+"\"}"; ;
            }
        }
        private String doPost(string url, string param) {
            return "";
        }

        /// <summary>
        /// 绘制二维码
        /// </summary>
        /// <param name="codeStr">二维码内容</param>
        /// <param name="size">二维码中每个小点的大小，建议10</param>
        /// <returns>Bitmap</returns>
        private Bitmap CreateImgCode(string codeStr,int size) {
            //创建二维码生成类  
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            //设置编码模式  
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            //设置编码测量度  
            qrCodeEncoder.QRCodeScale = size;
            //设置编码版本  
            qrCodeEncoder.QRCodeVersion = 0;
            //设置编码错误纠正  
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            //生成二维码图片  
            System.Drawing.Bitmap image = qrCodeEncoder.Encode(codeStr);
            return image;
        }

        private void checkLoginTimer_Tick(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 登录检测
        /// </summary>
        private void checkLogin()
        {
            JObject jo = (JObject)JsonConvert.DeserializeObject(doGet(check+"?log_id="+ log_id));
            if (jo != null)
            {
                if ((int)jo["status"] == 1)
                {
                    checkLoginPos = -1;
                    tsStateBar.Text = "登陆成功，正在获取报告单列表...";
                    user_id = (string)jo["data"]["user_id"];
                    getReports();
                }else
                {
                    //tsStateBar.Text = jo["msg"] + ", error code：" + jo["status"];    
                }
            }else
            {
                tsStateBar.Text = "很抱歉，数据请求失败了，请检查你的网络连接。";
            }
            //tsStateBar.Text = (new Random()).Next().ToString();
        }

        /// <summary>
        /// 获取报告单列表
        /// </summary>
        private void getReports()
        {
            JObject jo = (JObject)JsonConvert.DeserializeObject(doGet(reports + "?user_id=" + user_id + "&p="+currentPage));
            if (jo != null)
            {
                if ((int)jo["status"] == 1)
                {
                    try
                    {
                        string str = JsonConvert.SerializeObject(jo["data"]["data"]);
                        currentPage = Convert.ToInt32(JsonConvert.SerializeObject(jo["data"]["p"]).Replace("\"", ""));
                        pageSize = Convert.ToInt32(JsonConvert.SerializeObject(jo["data"]["num"]).Replace("\"", ""));
                        count = Convert.ToInt32(JsonConvert.SerializeObject(jo["data"]["count"]).Replace("\"", ""));
                        sumPage = Convert.ToInt32(JsonConvert.SerializeObject(jo["data"]["total_page"]).Replace("\"", ""));
                        bool isNext = Convert.ToBoolean(JsonConvert.SerializeObject(jo["data"]["next"]).Replace("\"", ""));
                        gbControl.Visible = true;
                        if (currentPage > 1)
                        {
                            btnPagePrev.Enabled = true;
                        }
                        else
                        {
                            btnPagePrev.Enabled = false;
                        }
                        if (isNext)
                        {
                            btnPageNext.Enabled = true;
                        }
                        else {
                            btnPageNext.Enabled = false;
                        }
                        lbPageText.Text = "共["+count+ "]条 第"+currentPage+"/"+ sumPage + "页";

                        ReportEntity[] reports = JsonConvert.DeserializeObject<ReportEntity[]>(str);
                        //MessageBox.Show(arr, "提示");
                        gbLogin.Visible = false;
                        dgvReports.DataSource = reports;
                        //DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
                        //btn.HeaderText = "操作";
                        //btn.Text = "打印";
                        //btn.UseColumnTextForButtonValue = true;
                        //DataGridViewColumnCollection cols = dgvReports.Columns;
                        //dgvReports.Columns.Remove(btn);
                        //dgvReports.Columns.Add(btn);

                        dgvReports.Visible = true;
                        refleshReportsPos = 1;

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "提示");
                    }

                }
                else
                {
                    tsStateBar.Text = jo["msg"] + ", error code:" + jo["status"];
                }
            }
            else {
                tsStateBar.Text = "很抱歉，数据请求失败了，请检查你的网络连接。";
            }
        }
        /// <summary>
        /// 自动获取新报告单并打印
        /// </summary>
        private void refleshReports() {
            JObject jo = (JObject)JsonConvert.DeserializeObject(doGet(newReports + "?user_id=" + user_id));
            if (jo != null)
            {
                if ((int)jo["status"] == 1)
                {
                    try
                    {
                        string str = JsonConvert.SerializeObject(jo["data"]);
                        ReportEntity[] reports = JsonConvert.DeserializeObject<ReportEntity[]>(str);
                        // MessageBox.Show(arr, "提示");
                        // gbLogin.Visible = false;
                        foreach(var report in reports) {
                            downloadFile(report);
                        }
                        tsStateBar.Text = "刷新列表数据成功，共[" + reports.Length + "]条新数据";
                        // 获取到新数据重置列表
                        currentPage = 1;
                        getReports();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "提示");
                    }

                }
                else
                {
                    tsStateBar.Text = jo["msg"] + ", error code:" + jo["status"];
                }
            }
            else
            {
                tsStateBar.Text = "很抱歉，数据请求失败了，请检查你的网络连接。";
            }
        }
        private void print_btn_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(lvReports.SelectedItems[0].SubItems[0].Text);
        }

        /// <summary>
        /// 计时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkTimer_Tick(object sender, EventArgs e)
        {
            // 登录检查
            if (checkLoginPos == 1 && --checkLoginDec <= 0) {
                checkLoginDec = 3;
                checkLogin();
            }

            // 每隔300秒刷新数据
            if (refleshReportsPos == 1 )
            {
                tsStateBar.Text = --refleshReportsDec + "秒后自动获取最新列表";
                if (refleshReportsDec <= 0)
                {
                    refleshReportsDec = 300;
                    refleshReports();
                }
            }
        }


        /// <summary>
        /// 点击列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvReports_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                try
                {

                    DataGridViewColumn column = dgvReports.Columns[e.ColumnIndex];
                    ReportEntity report = (ReportEntity)dgvReports.Rows[e.RowIndex].DataBoundItem;
                    if (column is DataGridViewButtonColumn)
                    {

                        downloadFile(report);
                        //MessageBox.Show(report.pdf_url);
                        //MessageBox.Show(dgvReports.Rows[e.RowIndex].Cells[e.ColumnIndex - 4].Value.ToString());
                    }
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        /// <summary>
        /// 打印记录
        /// </summary>
        /// <param name="order_id">报告单id</param>
        private void reportLog(string order_id) {
            doGet(log + "?order_id=" + order_id);
        }

        /// <summary>
        /// 下载pdf到本地
        /// </summary>                      
        /// <param name="report"></param>
        /// <param name="path"></param>
        private void downloadFile(ReportEntity report) {

            Application.DoEvents();
            refleshReportsPos = -1;//暂停刷新
            tsStateBar.Text = "正在获取PDF报告单数据...";
            string dirPath = currentDirPath + "\\报告单\\";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            string filePath = dirPath + report.sample_sn + ".pdf";
            if (!File.Exists(filePath))
            {
                if (string.IsNullOrEmpty(report.pdf_url))
                {
                    MessageBox.Show("PDF链接为空", "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                float percent = 0;
                try
                {
                    WebRequest req = (WebRequest)WebRequest.Create(report.pdf_url);
                    WebResponse res = (WebResponse)req.GetResponse();
                    long totalBytes = res.ContentLength;
                    progressBarLoading.Visible = true;
                    progressBarLoading.Maximum = (int)totalBytes;
                    Stream st = res.GetResponseStream();
                    Stream so = new FileStream(filePath, System.IO.FileMode.Create);
                    long totalDownloadedByte = 0;
                    byte[] by = new byte[1024];
                    int osize = st.Read(by, 0, (int)by.Length);
                    while (osize > 0)
                    {
                        totalDownloadedByte += osize;
                        Application.DoEvents();
                        so.Write(by, 0, osize);
                        if (progressBarLoading != null)
                        {
                            progressBarLoading.Value = (int)totalDownloadedByte;
                        }
                        osize = st.Read(by, 0, (int)by.Length);

                        percent = totalDownloadedByte / totalBytes * 100;
                        tsStateBar.Text = "正在下载PDF..." + percent.ToString("00.00") + "%";
                        Application.DoEvents(); //必须加注这句代码，否则label1将因为循环执行太快而来不及显示信息
                        if (percent == 100)
                        {
                            tsStateBar.Text = "PDF下载成功";
                            progressBarLoading.Visible = false;
                            //MessageBox.Show("下载完成", "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    so.Close();
                    st.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "消息提示1", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return ;
                }
            }
            if (!File.Exists(filePath))
            {
                MessageBox.Show("下载PDF失败了", "消息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                printPDF(report.order_id, filePath);
            }
        }

        private void delFile(string filePath) {
            if (File.Exists(filePath)) {
                File.Delete(filePath);
            }
        }

        /// <summary>
        /// 打印报告单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="filePath"></param>
        private void printPDF(string id,string filePath)
        {
            reportLog(id);
            tsStateBar.Text = "正在打印... " + id;
            Thread.Sleep(2000);
            getReports();
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile(filePath);
            pdf.Print();
            //pdf.PrintDocument.Print();
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPageNext_Click(object sender, EventArgs e)
        {
            currentPage = currentPage + 1 >= sumPage ? sumPage : ++currentPage;
            getReports();
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPagePrev_Click(object sender, EventArgs e)
        {
            currentPage = currentPage - 1 <= 1 ? 1 : --currentPage;
            getReports();
        }

        private void MainForm_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 116 && !string.IsNullOrEmpty(user_id)) {
                currentPage = 1;
                getReports();
            }
        }
    }

}
